#include "stalemate.h"

//main-------------------------------------------
int main(int argc, char* argv[]) {
    controll::getControll()->Run();
    return 0;
}
//main===========================================

//controll---------------------------------------
//statics---------------
controll* controll::ctrl;
string controll::fleetFolder;
string controll::saveFolder;
string controll::scnFolder;
screenManager controll::screenMan;
//constructors----------
controll* controll::getControll() {
    if (ctrl == NULL)
        ctrl = new controll();
    return ctrl;
}
controll::~controll() {
    SDL_FreeSurface(window);
    //clear the screen manager
    SDL_Quit();
}
//access----------------
string controll::getFleetFolder() {
    return fleetFolder;
}
string controll::getSaveFolder() {
    return saveFolder;
}
string controll::getScnFolder() {
    return scnFolder;
}
screenManager* controll::getScrManager() {
    return &screenMan;
}
//game controll---------
void controll::Run() {
    //varBlock
    SDL_Event event;
    //init screens------
    if (!screenLoader::loadScreens()) {
        cout << "could not load screens" << endl;
        cout.flush();
        exit(0);
    }
    //create update thread
    //controll loop
    update();
    while (!doQuit) {
        if (!pause) {
            while (SDL_PollEvent(&event)) {
                if (screenMan.getActiveScreen() != NULL) {
                    //cout << "passing event " << (int) event.type << " to active scr" << endl;
                    if (screenMan.getActiveScreen() != NULL && screenMan.getActiveScreen()->onEvent(&event)) {
                        update();
                    }
                }
                if (event.type == SDL_QUIT) {
                    doQuit = true;
                }
            }
        }
    }
}
void controll::update() {
    screenMan.getActiveScreen()->onUpdate(1.0);
    SDL_Flip(window);
}
//private cons----------
controll::controll() : doQuit(false), pause(false) {
    getFileNames();
    SDL_Init(SDL_INIT_EVERYTHING);
    //prepare the window
    window = SDL_SetVideoMode(1000, 500, 32, SDL_SWSURFACE | SDL_RESIZABLE);
    screenMan = screenManager(window);
}
//file functions--------
void controll::getFileNames() {
    fstream dfile(dataFile);
    string tok;

    while (dfile.good()) {
        dfile >> tok;
        if (tok.compare("FLT") == 0) {
            dfile >> fleetFolder;
        } else if (tok.compare("MAPS") == 0) {
            dfile >> scnFolder;
        } else if (tok.compare("SAVE") == 0) {
            dfile >> saveFolder;
        }
    }
    dfile.close();
}
//===============================================